package webTest.sessionCookie;

import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Date;

/**
 * Created by IFT8 on 2015/1/22.
 */
public class CookieDemo extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request, response);
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        Cookie cookie = new Cookie("lastTime", new Date().getTime() + "");
        cookie.setMaxAge(60*60*24);//以秒为单位，没有设置MaxAge就默认为会话级Cookie,0为删除
        response.addCookie(cookie);
        Cookie[] cookies = request.getCookies();
        String strLastTime=null;
        response.setContentType("text/html;charset=UTF-8");
        if (cookies == null) {
            return;
        }
        for (Cookie cookie1 : cookies) {
            if("lastTime".equals(cookie1.getName())){
                strLastTime=cookie1.getValue();
                break;
            }
        }
        if(strLastTime==null){
            response.getWriter().println("首次访问");
        }else{
            response.getWriter().println("上次访问时间为： "+new Date(Long.parseLong(strLastTime)).toString());
        }
    }
}
